import dotenv from 'dotenv';
import querystring from 'querystring'; // 用于 urlencode

dotenv.config();

// 检查百度 AI 的环境变量
if (!process.env.BAIDU_API_KEY || !process.env.BAIDU_SECRET_KEY) {
  throw new Error('BAIDU_API_KEY 或 BAIDU_SECRET_KEY 环境变量未设置');
}

const BAIDU_CLIENT_ID = process.env.BAIDU_API_KEY;
const BAIDU_CLIENT_SECRET = process.env.BAIDU_SECRET_KEY;

const TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token';
const IMAGE_UNDERSTANDING_REQUEST_URL = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request';
const IMAGE_UNDERSTANDING_GET_RESULT_URL = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result';

let cachedToken: { access_token: string; expires_at: number } | null = null;

// Helper function for delaying execution
const delay = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));

const getAccessToken = async (): Promise<string> => {
  const now = Date.now();
  if (cachedToken && cachedToken.expires_at > now + 60 * 1000) {
    return cachedToken.access_token;
  }
  console.log('正在获取新的百度 Access Token...');
  const tokenUrl = `${TOKEN_URL}?grant_type=client_credentials&client_id=${BAIDU_CLIENT_ID}&client_secret=${BAIDU_CLIENT_SECRET}`;
  try {
    const response = await fetch(tokenUrl, { 
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
     }); 
    if (!response.ok) {
      const errorBody = await response.json().catch(() => ({}));
      throw new Error(`获取 Access Token 失败: ${response.status} ${errorBody?.error_description || '未知错误'}`);
    }
    const tokenData = await response.json();
    if (!tokenData.access_token || !tokenData.expires_in) {
        throw new Error('获取 Access Token 失败: 响应格式无效');
    }
    cachedToken = {
      access_token: tokenData.access_token,
      expires_at: now + tokenData.expires_in * 1000
    };
    console.log('成功获取并缓存了百度 Access Token。');
    return cachedToken.access_token;
  } catch (error) {
    console.error('获取百度 Access Token 时出错:', error);
    cachedToken = null;
    throw new Error(`获取百度 Access Token 时发生错误: ${error instanceof Error ? error.message : '未知错误'}`);
  }
};

/**
 * 使用 fetch 调用百度 AI 图像理解 API 分析图像 (异步轮询)
 * @param base64DataUrl 带前缀的 Base64 编码图像数据 URL (e.g., "data:image/png;base64,...")
 * @returns AI 的分析结果 (description)
 */
export const recognizeImageBaidu = async (base64DataUrl: string): Promise<string> => {
  const accessToken = await getAccessToken();
  const pureBase64 = base64DataUrl.replace(/^data:image\/\w+;base64,/, "");

  // 1. 提交图像理解请求
  const requestUrl = `${IMAGE_UNDERSTANDING_REQUEST_URL}?access_token=${accessToken}`;
  const requestBody = {
    image: pureBase64,
    question: "这是一个你画我猜游戏,请根据图片内容给出答案,答案请用中文回答,要回答具体的事物,不要回答抽象的词语"
  };

  console.log('开始调用百度图像理解 API (提交请求)...');
  let taskId: string;
  try {
    const requestResponse = await fetch(requestUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(requestBody)
    });

    if (!requestResponse.ok) {
      const errorBody = await requestResponse.json().catch(() => ({}));
      throw new Error(`百度图像理解请求提交失败: ${requestResponse.status} ${errorBody?.error_msg || '未知错误'}`);
    }

    const requestData = await requestResponse.json();
    if (!requestData.result || !requestData.result.task_id) {
       console.error('百度图像理解 API 提交请求响应格式无效:', requestData);
       if(requestData.error_code) {
           throw new Error(`百度图像理解提交失败: ${requestData.error_msg} (code: ${requestData.error_code})`);
       }
      throw new Error('百度图像理解 API 未返回有效的 task_id');
    }
    taskId = requestData.result.task_id;
    console.log(`成功提交图像理解任务, Task ID: ${taskId}`);

  } catch (error) {
    console.error('调用百度图像理解 API (提交请求) 时出错:', error);
    throw new Error(`调用百度 AI 图像理解服务 (提交请求) 失败: ${error instanceof Error ? error.message : '未知错误'}`);
  }

  // 2. 轮询获取结果
  const getResultUrl = `${IMAGE_UNDERSTANDING_GET_RESULT_URL}?access_token=${accessToken}`;
  const getResultBody = { task_id: taskId };
  const maxRetries = 10;
  const retryDelay = 2000;

  console.log('开始轮询获取图像理解结果...');
  for (let i = 0; i < maxRetries; i++) {
    try {
      await delay(retryDelay);
      console.log(`正在进行第 ${i + 1} 次轮询... (Task ID: ${taskId})`);

      const resultResponse = await fetch(getResultUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(getResultBody)
      });

      if (!resultResponse.ok) {
        const errorBody = await resultResponse.json().catch(() => ({}));
        
        console.warn(`轮询百度图像理解结果失败: ${resultResponse.status} ${errorBody?.error_msg || '未知错误'} (Attempt ${i+1}/${maxRetries})`);
        
        if (i === maxRetries - 1) {
             throw new Error(`轮询百度图像理解结果失败 (已达最大重试次数): ${resultResponse.status} ${errorBody?.error_msg || '未知错误'}`);
        }
        continue;
      }

      const resultData = await resultResponse.json();

      if (resultData.result && resultData.result.ret_code === 0) {
        if (resultData.result.description) {
          const guess = resultData.result.description;
          console.log(`百度 AI 图像理解结果: ${guess}`);
          return guess;
        } else {
          console.error('百度图像理解 API 返回成功但无 description:', resultData);
          throw new Error('百度图像理解 API 返回成功但未包含有效描述');
        }
      } else if (resultData.result && resultData.result.ret_code === 1) {
        console.log(`任务仍在处理中 (Attempt ${i+1}/${maxRetries})...`);
        if (i === maxRetries - 1) {
             throw new Error('获取百度图像理解结果超时 (已达最大重试次数)');
        }
      } else {
         console.error('百度图像理解 API 获取结果响应格式无效或包含错误:', resultData);
         if(resultData.error_code && resultData.error_msg) {
            throw new Error(`获取百度图像理解结果失败: ${resultData.error_msg} (code: ${resultData.error_code})`);
         }
         throw new Error('百度图像理解 API 获取结果响应无效或遇到未知错误');
      }
    } catch (error) {
        console.error(`轮询百度图像理解 API (获取结果) 第 ${i + 1} 次时出错:`, error);
        
        if (i === maxRetries - 1) {
            throw new Error(`轮询百度 AI 图像理解服务 (获取结果) 失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
    }
  }

  throw new Error('获取百度图像理解结果超时');
}; 